<!-- 小智同学 -->
<template>
  <div>
    <van-nav-bar title="小智同学" left-arrow @click-left="$router.back()" />

    <van-cell-group class="talk" ref="talk">
      <van-cell
        :title="val.msg"
        v-for="(val, i) in messages"
        :key="i"
        :class="val.flag == 'user' ? 'me' : 'robot'"
      />
    </van-cell-group>

    <van-cell-group class="submit">
      <van-field v-model="message" @keydown.enter="onSend" />
      <van-button type="primary" @click="onSend">发表</van-button>
    </van-cell-group>
  </div>
</template>

<script>
import io from "socket.io-client";
import { Toast } from "vant";
import store from "../../store";
import { getItem, setItem } from "../../utils/storage";
export default {
  name: "UserChat",
  data() {
    return {
      message: "",
      socket: null,
      messages: getItem("messages") || [],
    };
  },
  methods: {
    onSend() {
      const data = {
        msg: this.message,
        timestamp: Date.now(),
        flag: 'user'
      };
      this.socket.emit("message", data);
      this.messages.push(data);
      this.message = "";
    },
    scrollToBottom() {
      const list = this.$refs["talk"];
      list.scrollTop = list.scrollHeight;
      console.log(list.scrollHeight);
    },
  },
  mounted() {
    // 建立连接
    try {
      this.socket = io("http://toutiao.itheima.net", {
        query: {
          token: store.state.userInfo.token,
        },
        transports: ["websocket"],
      });
      window.socket = this.socket;
      this.socket.on("connect", () => {
        console.log("连接成功");
      });
      this.socket.on("message", (data) => {
        console.log("接收到的信息", data);
        data.flag = 'robot'
        this.messages.push(data);
      });
      this.scrollToBottom();
    } catch (error) {
      Toast.fail("连接出错")
      this.$router.back()
    }

  },
  watch: {
    messages(val) {
      setItem("messages", this.messages);
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
  },
};
</script>

<style lang="less" scoped>
.talk {
  position: fixed;
  top: 47px;
  left: 0;
  right: 0;
  bottom: 64px;
  overflow: auto;
}
.submit {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 10px;
  justify-content: space-between;
  align-items: center;
  .van-field {
    border: none;
  }
  .van-button {
    width: 55px;
    font-size: 13px;
    padding: 10px;
  }
}
.me {
  span {
    background-color: rgb(16, 218, 16);
    padding: 5px 15px;
    border-radius: 25px;
    color: white;
    float: right;
  }
}
.robot {
  span {
    background-color: rgb(184, 181, 181);
    padding: 5px 15px;
    border-radius: 25px;
    color: black;
    float: left;
  }
}
</style>